//
//  SearchViewController.m
//  ScrollView
//
//  Created by antl on 1/4/13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "SearchViewController.h"
#import "GlobalConfig.h"
#import "GADBannerView.h"
#import "GADRequest.h"
@implementation SearchViewController
@synthesize mscrollview;
@synthesize ipTabBar;
@synthesize adBanner;
static SearchViewController *SearchViewControllerInstance=nil;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
         self.tabBarItem.image = [UIImage imageNamed:@"bar_info.png"];
        [self initData];
        UITapGestureRecognizer *tapGesture =[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disablePickerView)] autorelease];
        tapGesture.numberOfTapsRequired=2;
        [self.view addGestureRecognizer:tapGesture];
        SearchViewControllerInstance=self;
    }
    return self;
}
+(SearchViewController*)getSearchViewControllerInstance
{
    return SearchViewControllerInstance;
}
-(void)disablePickerView
{
    if(isEnablePickerView==FALSE){return;}
    isEnablePickerView=FALSE;
    [pickerView setHidden:TRUE];
    [self addTabBar];
}
#pragma mark - View lifecycle
-(void)addTabBar
{
    float yPosOff, yPosOn, tbWidth;
    int result=[GlobalConfig getOrient];
    BOOL isCurrentlyLandscapeView=FALSE;
    if(result==-1)
    {
        UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
        isCurrentlyLandscapeView=UIDeviceOrientationIsLandscape(deviceOrientation);
    }
    else if(result==0)// landscape
    {
        isCurrentlyLandscapeView=TRUE;
    }
    else if(result==1)// portrait
    {
        isCurrentlyLandscapeView=FALSE;
    }
    
    
	//UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
	if (isCurrentlyLandscapeView==TRUE) {
        if (IS_IPHONE5) {
           yPosOff = LANDSCAPE_HEIGHT;
            yPosOn = 250;
            tbWidth = 586;//480;
        }
        else
        {
            yPosOff = LANDSCAPE_HEIGHT;
            yPosOn = 250;
            tbWidth = 480;//480;
        }
	} else {
        if (IS_IPHONE5) {
            yPosOff =500 ;
            yPosOn = 500;
            tbWidth = 320;
        }
        else
        {
            yPosOff =410 ;
            yPosOn = 410;
            tbWidth = 320;
        }
	}
    if(!ipTabBar)
    {

        ipTabBar = [[IPLibTabBar alloc] initWithFrame:CGRectMake(0, 0, 0, TABBAR_HEIGHT)];
        ipTabBar.delegate = self;
        [self.view addSubview:ipTabBar];
        [UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.05];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
		ipTabBar.frame = CGRectMake(0, yPosOn, tbWidth, TABBAR_HEIGHT);
		[UIView commitAnimations];
		[ipTabBar release];
    }
    else {
		
		[UIView animateWithDuration:0.01
							  delay:0.0 
							options:UIViewAnimationOptionCurveEaseOut
						 animations:^{
							 ipTabBar.frame = CGRectMake(ipTabBar.frame.origin.x, yPosOff, tbWidth, TABBAR_HEIGHT);
						 }
						 completion:^(BOOL finished){
							 ipTabBar.delegate = nil;
							 [ipTabBar removeFromSuperview];
							 ipTabBar = nil;
						 }
		 ];
		
	}
    
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
	
 
    SAFE_RELEASE(m_Sheet);
	switch (item.tag) {
		case tagTABBAR_1:
			NSLog(@"TabBar_1");            
			break;
		case tagTABBAR_2:
            [self jumpToPage:2];
            NSLog(@"TabBar_2");
            break;
			break;
        case tagTABBAR_4:
           [self addTabBar];
            [self addActionSheetwithAnimation:YES];
			break;
		default:
			break;
	}
	
}
-(void)jumpToPage:(int)iN
{
    if(storeController==nil)
    {
        storeController = [[StoreViewController alloc] initWithNibName:@"StoreViewController" bundle:[NSBundle mainBundle]] ;
    }   
    [APP_DELEGATE.navCtrlr pushViewController:storeController animated:YES];
}
#pragma mark - Add-Banner
-(void)addBanner
{
    CGPoint origin = CGPointMake(0,0);
    //self.view.frame.size.height - CGSizeFromGADAdSize(kGADAdSizeBanner).height
    // Use predefined GADAdSize constants to define the GADBannerView.
    self.adBanner = [[[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner origin:origin] autorelease];
    // Note: Edit SampleConstants.h to provide a definition for kSampleAdUnitID
    // before compiling.
    self.adBanner.adUnitID = kSampleAdUnitID;
    //[self.adBanner setBackgroundColor:[UIColor blackColor]];
    self.adBanner.delegate = self;
    [self.adBanner setRootViewController:self];
    [self.view addSubview:self.adBanner];
   // self.adBanner.center = CGPointMake(self.view.center.x, self.adBanner.center.y);
    [self.adBanner loadRequest:[self createRequest]];
}
-(void)setPositionBanner:(BOOL)isLandScape
{
    if (IS_IPHONE5)
    {
        if(isLandScape==TRUE)
        {
             self.adBanner.frame=CGRectMake(0, 0, /*self.adBanner.frame.size.width+160*/568, self.adBanner.frame.size.height);
           
        }
        else{
            self.adBanner.frame=CGRectMake(0, 0, /*self.adBanner.frame.size.width+160*/320, self.adBanner.frame.size.height);
        }
    }
    else
    {
        if(isLandScape==TRUE)
        {
             self.adBanner.frame=CGRectMake(0, 0, /*self.adBanner.frame.size.width+160*/480, self.adBanner.frame.size.height);
        }
        else{
             self.adBanner.frame=CGRectMake(0, 0, /*self.adBanner.frame.size.width+160*/320, self.adBanner.frame.size.height);
        }
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];    
    [self addLable];
    [self addTabBar];
    [self addBanner];
    isEnablePickerView=FALSE;
    if (IS_IPHONE5) {
         mscrollview.frame = CGRectMake(0, 0, 568, 460);
    }
    else
    {        
        mscrollview.frame = CGRectMake(0, 0, 320, 460);
      
    }
    [mscrollview setBackgroundColor:[UIColor clearColor]];
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    BOOL isCurrentlyLandscapeView = UIDeviceOrientationIsLandscape(deviceOrientation);

    if(isCurrentlyLandscapeView==TRUE)
    {        
       mscrollview.contentSize = CGSizeMake(320, 500+[GlobalConfig getAddLandScapeFor:0]);
        [self setpositionLableLandScape:TRUE];
        [self setPositionBanner:TRUE];
    }
    else
    {
        mscrollview.contentSize = CGSizeMake(320, 500+[GlobalConfig getAddPortraitFor:0]);
        [self setpositionLableLandScape:FALSE];
        [self setPositionBanner:FALSE];
        
    }

    [self setLableLanguageForSearchScene];
}
#pragma mark ------------- AN ------
-(void)positionLanguage
{
     
    int result=[GlobalConfig getOrient];
    BOOL isCurrentlyLandscapeView=FALSE;
    if(result==-1)
    {
        UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
        isCurrentlyLandscapeView=UIDeviceOrientationIsLandscape(deviceOrientation);
    }
    else if(result==0)// landscape
    {
        isCurrentlyLandscapeView=TRUE;
    }
    else if(result==1)// portrait
    {
        isCurrentlyLandscapeView=FALSE;
    }    
    if(isCurrentlyLandscapeView==TRUE)
    {        
        mscrollview.contentSize = CGSizeMake(320, 500+[GlobalConfig getAddLandScapeFor:0]);
        [self setpositionLableLandScape:TRUE];
        [self tabbarPosition:TRUE];
        [self setPositionBanner:TRUE];
    }
    else
    {
        mscrollview.contentSize = CGSizeMake(320, 500+[GlobalConfig getAddPortraitFor:0]);
        [self setpositionLableLandScape:FALSE];
        [self tabbarPosition:FALSE];
        [self setPositionBanner:FALSE];
        
    }
    
    [self setLableLanguageForSearchScene];
    
}
-(void)tabbarPosition:(BOOL)landscape
{
    if(landscape==TRUE)
    {
        if (IS_IPHONE5) {
            ipTabBar.frame = CGRectMake(0, 250, 568, TABBAR_HEIGHT);
        }else
        {
            ipTabBar.frame = CGRectMake(0, 250, 480, TABBAR_HEIGHT);
            
        }
		
    }
    else
    {
        if (IS_IPHONE5) {
             ipTabBar.frame = CGRectMake(0,500 , 320, TABBAR_HEIGHT);
        }else
        {
            ipTabBar.frame = CGRectMake(0,410 , 320, TABBAR_HEIGHT);
            
        }

    }
}
-(void)setLableLanguageForSearchScene
{
    // NSLog(@"APP_DELEGATE.langId =%@",APP_DELEGATE.langId);
    NSString *STR=APP_DELEGATE.langId;//@"eng";//@"vn"
    Title.text          =GET_STRING(@"SEARCH_TITLE", STR); 
    titleSearch.text    =GET_STRING(@"SEARCH_NAME", STR); 
    titleTag.text       =GET_STRING(@"TITLE_TAG", STR); 
    if([STR isEqualToString:@"eng"])
    {
        UIImage *img1 = [GlobalConfig drawText:GET_STRING(@"BUTTON_SEARCH", STR)
                                       inImage:[UIImage imageNamed:@"btn-test-0.png"] //btImage.png
                                       atPoint:CGPointMake(36, 12)];
        [Search setImage:img1 forState:UIControlStateNormal];
        
    }
    else
    {
        UIImage *img1 = [GlobalConfig drawText:GET_STRING(@"BUTTON_SEARCH", STR)
                                  inImage:[UIImage imageNamed:@"btn-test-0.png"] //btImage.png
                                  atPoint:CGPointMake(35, 12)];
        [Search setImage:img1 forState:UIControlStateNormal];
        //[Search setBackgroundColor:[UIColor blackColor]];
    }
    
    if([STR isEqualToString:@"eng"])
    {
        UIImage *img2 = [GlobalConfig drawText:GET_STRING(@"BUTTON_SAVE", STR)
                                       inImage:[UIImage imageNamed:@"btn-test-0.png"] //btImage.png
                                       atPoint:CGPointMake(50, 12)];
        [Saving setImage:img2 forState:UIControlStateNormal];
        //[Saving setBackgroundColor:[UIColor blackColor]];
    }
    else
    {
        UIImage *img2 = [GlobalConfig drawText:GET_STRING(@"BUTTON_SAVE", STR)
                                   inImage:[UIImage imageNamed:@"btn-test-0.png"] //btImage.png
                                   atPoint:CGPointMake(20, 12)];
        [Saving setImage:img2 forState:UIControlStateNormal];
        //[Saving setBackgroundColor:[UIColor blackColor]];
    
    }
    
    ChoiceTag.text=[arrayTag objectAtIndex:0];
}

- (UIActionSheet*)getSettingSheet
{
	UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                       delegate:self
                                              cancelButtonTitle:nil
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:nil]  ;
	
	sheet.tag = 100;	
    NSString *STR=APP_DELEGATE.langId;
   // NSLog(@"str =%@",STR);
    if([STR isEqualToString:@"vn"])
    {
        [sheet addButtonWithTitle:@"Tiếng Anh"];
        [sheet addButtonWithTitle:@"Tiếng Việt"];
        [sheet addButtonWithTitle:@"Thoát"];
    }
    else
    {
        [sheet addButtonWithTitle:@"English"];
        [sheet addButtonWithTitle:@"VietNamese"];
        [sheet addButtonWithTitle:@"Cancle"];
    }
    


    [sheet setCancelButtonIndex:2];
    
    
	return sheet;
}
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    

    
    if(buttonIndex == 0) 
    {
        [APP_DELEGATE setLangId:@"eng"];
       /// choice English
        // remove add add tabbar
        
    
    }
    else if(buttonIndex==1){
       //Choice Vietnamese        
        [APP_DELEGATE setLangId:@"vn"];
        // remove add add tabbar
        
    }
    else if(buttonIndex==2)
    {
        ///cancel
    }
    [self addTabBar];
    [self setLableLanguageForSearchScene];
    if([SearchViewController getSearchViewControllerInstance].ipTabBar!=nil)
    {
        UITabBarItem *item= [[SearchViewController getSearchViewControllerInstance].ipTabBar.items objectAtIndex:0];        
        [[SearchViewController getSearchViewControllerInstance].ipTabBar setSelectedItem:item];
    }
}
-(void)addActionSheetwithAnimation:(BOOL)bValue
{
    
    if(bValue==TRUE)
    {
        
        if(m_Sheet!=nil)
        {
            [m_Sheet removeFromSuperview];
        }
        SAFE_RELEASE( m_Sheet );
        m_Sheet = [self getSettingSheet] ;
        [m_Sheet showFromTabBar:ipTabBar];
       
    }
    
}
#pragma mark - ADD LABLE
-(void)addLable
{
    ////Title
    Title = [[UILabel alloc ] init];
    Title.textAlignment =  UITextAlignmentCenter;
    Title.textColor = [UIColor whiteColor];
    Title.backgroundColor=[UIColor clearColor];
    Title.font = [UIFont fontWithName:@"Arial" size:(19.0)];
    Title.frame=CGRectMake(0, 0, 256, 100);
    [mscrollview addSubview:Title];
    /// title search
    titleSearch = [[UILabel alloc ] init];
    titleSearch.textAlignment =  UITextAlignmentLeft;
    titleSearch.textColor = [UIColor whiteColor];
    titleSearch.backgroundColor=[UIColor clearColor];
    titleSearch.font = [UIFont fontWithName:@"Arial" size:(17.0)];
    titleSearch.frame=CGRectMake(0, 0, 200, 100);
    [mscrollview addSubview:titleSearch];
    ///// text Field
    inputDomain=[[UITextField alloc] initWithFrame:CGRectMake(11, 130, 299, 31)];
    inputDomain.delegate=self;
    inputDomain.autocorrectionType = UITextAutocorrectionTypeNo;
   // inputDomain.autocorrectionType = FALSE;
    inputDomain.autocapitalizationType = UITextAutocapitalizationTypeNone;
    inputDomain.textAlignment=UITextAlignmentCenter;
    [inputDomain setBackgroundColor:[UIColor whiteColor]];
    [mscrollview addSubview:inputDomain];
    /// title tag
    titleTag = [[UILabel alloc ] init];
    titleTag.textAlignment =  UITextAlignmentLeft;
    titleTag.textColor = [UIColor whiteColor];
    titleTag.backgroundColor=[UIColor clearColor];
    titleTag.font = [UIFont fontWithName:@"Arial" size:(17.0)];
    titleTag.frame=CGRectMake(0, 0, 200, 100);
    [mscrollview addSubview:titleTag];
    ///text field choice tag 
    ChoiceTag=[[UITextField alloc] initWithFrame:CGRectMake(11, 180, 299, 31)];
    ChoiceTag.delegate=self;
    ChoiceTag.autocorrectionType = UITextAutocorrectionTypeNo;//FALSE;
    ChoiceTag.autocapitalizationType = UITextAutocapitalizationTypeNone;
    ChoiceTag.textAlignment=UITextAlignmentCenter;
    [ChoiceTag setBackgroundColor:[UIColor whiteColor]];
    [mscrollview addSubview:ChoiceTag];
    /// button seacrch        
    
    
    
    
    Search = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    [Search addTarget:self action:@selector(searching:) forControlEvents:UIControlEventTouchDown];        
    [mscrollview addSubview:Search];
    /// button Saving
   
    
    
    
    
    
    Saving= [[UIButton buttonWithType:UIButtonTypeCustom] retain];
   /// [Saving setImage:img forState:UIControlStateNormal];
    [Saving addTarget:self action:@selector(saving:) forControlEvents:UIControlEventTouchDown];        
    [mscrollview addSubview:Saving];
    
    
    
    ///small Button
    smallButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    [smallButton addTarget:self action:@selector(enablePickerView:) forControlEvents:UIControlEventTouchDown]; 
    
    UIImage *img = [GlobalConfig drawText:@"ß"
                                   inImage:[UIImage imageNamed:@"btNeed.png"] 
                                   atPoint:CGPointMake(15, 10)];
    [smallButton setImage:img forState:UIControlStateNormal];
    //[smallButton setTitle:@"P" forState:UIControlStateNormal];
    
    
    [mscrollview addSubview:smallButton];
    
    /// picker view   
    pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 0, 247)];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;    
    [self.view addSubview:pickerView];
    [pickerView setHidden:TRUE];
   
}

-(void)saving:(id)sender
{
    
    if([inputDomain.text isEqualToString:@""]!=TRUE&&[ChoiceTag.text isEqualToString:@""]!=TRUE&&inputDomain.text!=nil&&ChoiceTag.text!=nil)
    {
        [GlobalConfig setLink:[NSString stringWithFormat:@"%@%@",inputDomain.text,[self convertMyString]]];
    }
    
    
    NSString *str=[GlobalConfig getLink];
     NSLog(@"saving %@",str);
    if([str isEqualToString:@""]||str==nil)
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:nil
                              message: GET_STRING(@"ERROR_SEARCH", APP_DELEGATE.langId)
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray* array = [defaults objectForKey:kData];

    NSMutableArray *savingArray=[[NSMutableArray alloc] initWithCapacity:0];
    BOOL isAdd=TRUE;
    if(array==nil||[array count]==0)
    {
        // chua co du lieu
        
    }
    else
    {
        for (int index=0; index<[array count]; index++) {
            [savingArray addObject:[array objectAtIndex:index]];
            if([[GlobalConfig getLink] isEqualToString:[array objectAtIndex:index]]==TRUE)
            {
                isAdd=FALSE;
            }
            
            
        }
    }
    if(isAdd==TRUE)
    {
        [savingArray addObject:[NSString stringWithFormat:@"%@",[GlobalConfig getLink]]];
        [defaults setObject:savingArray forKey:kData];
        [defaults synchronize];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:nil
                              message: GET_STRING(@"CANT_SAVE", APP_DELEGATE.langId)
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];

    }
    SAFE_RELEASE(savingArray);
    
    BOOL finding=FALSE;
    
    NSMutableArray* array_1 =[defaults objectForKey:kData];
    for (int index=0; index<[array_1 count]; index++) {
        //NSLog(@"%@",[array_1 objectAtIndex:index]);
        
        if([[GlobalConfig getLink] isEqualToString:[array_1 objectAtIndex:index]]==TRUE)
        {
            finding=TRUE;
            break;
        }
    }
    
    if(finding==TRUE&&isAdd==TRUE)
    {
        
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:nil
                              message: GET_STRING(@"SUCCESS_SAVING", APP_DELEGATE.langId)
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else if(finding==FALSE&&isAdd==TRUE)
        
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:nil
                              message: GET_STRING(@"Error_SAVING", APP_DELEGATE.langId)
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
        
        
    
        
}

-(void)enablePickerView:(id)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    if(isEnablePickerView==FALSE)
    {
        isEnablePickerView=TRUE;
        [pickerView setHidden:FALSE];
        
    }
    else
    {
        isEnablePickerView=FALSE;
        [pickerView setHidden:TRUE];
    }
    [self addTabBar];
    
}
-(void)searching:(id)sender
{
    NSLog(@"searching");
   [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    if([inputDomain.text isEqualToString:@""]==TRUE||[ChoiceTag.text isEqualToString:@""]==TRUE||inputDomain.text==nil||ChoiceTag.text==nil)
    {
        //Ten.text=@"";
        // alert view
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:nil
                              message: GET_STRING(@"ERROR_SEARCH", APP_DELEGATE.langId)
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        
    }
    else
    {
    
        [self addRequestbyString:[NSString stringWithFormat:@"%@%@",inputDomain.text,[self convertMyString]] type:TYPE];
        SAFE_RELEASE(activity);
        activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [activity setFrame:[GlobalConfig getRectIndicator:(UIInterfaceOrientation)[UIDevice currentDevice].orientation andIsGetCurrentOrient:YES]];
        [activity startAnimating];
        [self.view addSubview:activity];
        [activity setBackgroundColor:[UIColor blackColor]];
        [activity setAlpha:0.6];
        
        
       
    }
    
    
}
-(NSString *)convertMyString
{
    if(ChoiceTag.text==nil)
    {
        ChoiceTag.text=@".com";
    }
    
    NSString *strXL=ChoiceTag.text;
    strXL = [strXL stringByReplacingOccurrencesOfString:@" " withString:@""];
    int index=[GlobalConfig getIndexDot:strXL];
    NSLog(@"index =%d",index);
    if(index==0)
    {
        /// append dot o truoc
        strXL=[NSString stringWithFormat:@".%@",strXL];
    }
    else if(index>1)
    {
        /// remove toi t .
        strXL = [strXL substringWithRange:NSMakeRange(index-1, [strXL length]-index+1)];
    }
    return strXL;

}
#pragma mark -
#pragma mark - Picker View Delegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
	
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
	
	return [arrayTag count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	
    
	return [arrayTag objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
	
	NSLog(@"Selected Color: %@. Index of selected color: %i", [arrayTag objectAtIndex:row], row);
    ChoiceTag.text=[arrayTag objectAtIndex:row];
    
}

#pragma mark - REQUEST INFOR
-(void)addRequestbyString:(NSString*)str type:(NSString*)Type
{
    NSString * searching=[NSString stringWithFormat:@"%@%@%@",HTTP,str,Type];  
    [GlobalConfig setLink:str];

    //NSLog(@"Searching =%@ ",searching);
    NSURL *treeURL =[NSURL URLWithString:[searching stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    ASIHTTPRequest * request= [ASIHTTPRequest requestWithURL:treeURL];
    [request setDelegate:self];
    [request setTimeOutSeconds:10.0];
    [request startAsynchronous];    
    self.view.userInteractionEnabled=NO;//disable
}
-(void)requestFailed:(ASIHTTPRequest *)request
{
    [activity stopAnimating];
    [activity removeFromSuperview];
    activity = nil;
    NSLog(@"%@",[request error]);
    self.view.userInteractionEnabled=YES;//enable
    
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:nil
                          message:GET_STRING(@"SEARCH_ERROR", APP_DELEGATE.langId)
                          delegate: nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    
}

-(void)requestFinished:(ASIHTTPRequest *)arequest
{
    
    
    NSString *responseString = [arequest responseString];
     if([responseString isEqualToString:@"True"])
    {
        /// is Resiter
        NSString *str=GET_STRING(@"SEARCH_HAVE", APP_DELEGATE.langId);
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil
                              message:[NSString stringWithFormat:@"%@ %@",[GlobalConfig getLink],str]
                              delegate: self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:@"Visit Page",nil];
        alert.tag=tag_Success;
        [alert show];
        [alert release];

              
    }
    else if([responseString isEqualToString:@"False"])
    {
        self.view.userInteractionEnabled=YES;//enable
        NSString *str=GET_STRING(@"SEARCH_NO", APP_DELEGATE.langId);
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:nil
                              message:[NSString stringWithFormat:@"%@ %@",[GlobalConfig getLink],str]
                              delegate: self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:@"Save",nil];
        alert.tag=tag_No;
        [alert show];
        [alert release];
        
        
    }
    
    
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    

    [activity stopAnimating];
    [activity removeFromSuperview];
    activity = nil;
    self.view.userInteractionEnabled=YES;
    if(alertView.tag==tag_Success)
    {
        if (buttonIndex == 0)
        {
            //Code for OK button
            [alertView dismissWithClickedButtonIndex:0 animated:YES];
        
        }
        if (buttonIndex == 1)
        {
            /// visit Page
            NSLog(@"visit link =%@",[GlobalConfig getLink]);
            NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"http://www.%@/",[GlobalConfig getLink]]]; /// test lai coi chung error
            [[UIApplication sharedApplication] openURL:url];
            //Code for download button
        }
    }
    else if(alertView.tag==tag_No)
    {
        if (buttonIndex == 0)
        {
            //Code for OK button
             [alertView dismissWithClickedButtonIndex:0 animated:YES];
        }
        if (buttonIndex == 1)
        {
            ///Saving
            //Code for download button
           [self saving:nil];
            
        }
    }
        
    
    
}
#pragma mark - TEXT FIED DELEGATE
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    
	return TRUE;    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
      return YES;
}
#pragma mark - For IOS 6 ---
- (BOOL) shouldAutorotate
{
    //NSLog(@"dasdhsa");
    return YES;
}
//- (NSUInteger)supportedInterfaceOrientations {
//    // NSLog(@"kkkkkkkkkk");
//    return UIInterfaceOrientationMaskAll;
//}
//
//
//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
//{
//    // NSLog(@"yyyyyy");
//    return UIInterfaceOrientationMaskPortrait;
//}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self repositionTabBar:toInterfaceOrientation];
    [activity setFrame:[GlobalConfig getRectIndicator:toInterfaceOrientation andIsGetCurrentOrient:NO]];

    if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
        
        [self changeTheViewToPortrait:YES andDuration:duration];
        [GlobalConfig setOrient:1];
        
    }
    else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeRight || toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        
        [self changeTheViewToPortrait:NO andDuration:duration];
        [GlobalConfig setOrient:0];
    }
}
- (void) changeTheViewToPortrait:(BOOL)portrait andDuration:(NSTimeInterval)duration{
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration];
    
    if(portrait){
        //change the view and subview frames for the portrait view
        
        mscrollview.contentSize = CGSizeMake(320, 500+[GlobalConfig getAddPortraitFor:0]);//-80
        [self setpositionLableLandScape:FALSE];
        [self setPositionBanner:FALSE];
        
        
    }
    else{   
        //change the view and subview  frames for the landscape view
        mscrollview.contentSize = CGSizeMake(320, 500+[GlobalConfig getAddLandScapeFor:0]);//-180
       [self setpositionLableLandScape:TRUE];
        [self setPositionBanner:TRUE];
        
    }
    
    [UIView commitAnimations];
}

-(void)dealloc
{
   // adBanner_.delegate = nil;
   // [adBanner_ release];
    [super dealloc];
    SAFE_RELEASE(arrayTag);
    SAFE_RELEASE(Title);
    SAFE_RELEASE(titleSearch);
    SAFE_RELEASE(inputDomain);
    SAFE_RELEASE(titleTag);
    SAFE_RELEASE(ChoiceTag);
    SAFE_RELEASE(Search);  
    SAFE_RELEASE(m_Sheet);
    [GlobalConfig setOrient:-1];
}

-(void)setpositionLableLandScape:(BOOL)isLandScape
{
    if (IS_IPHONE5) {
        if(isLandScape==TRUE)
        {
            Title.center        =CGPointMake(250+35, 30+40);///center
            titleSearch.center  =CGPointMake(110+35, 80);/// left
            inputDomain.frame   =CGRectMake(11+35, 100, 460, 24);//center
            titleTag.center     =CGPointMake(110+35, 150);/// left
            ChoiceTag.frame     =CGRectMake(11+35, 170, 460-40, 24);//center
            Search.frame        =CGRectMake(50+10+35, 205, 100, 40);//button
            Saving.frame        =CGRectMake(340-70+35, 205, 100, 40);//button
            smallButton.frame   =CGRectMake(435+35, 160, 38, 38);//button
            pickerView.frame    =CGRectMake(0+35, 150, 480, 247);
        }
        else{
            Title.center        =CGPointMake(160, 30+50);/// center
            titleSearch.center  =CGPointMake(110, 100+20);/// left
            inputDomain.frame   =CGRectMake(11, 130+20, 299, 24);//center
            titleTag.center     =CGPointMake(110, 180+20);/// left
            ChoiceTag.frame     =CGRectMake(11, 210, 299-40, 24);//center
            Search.frame        =CGRectMake(30-10, 250, 100, 40.0);//button
            Saving.frame        =CGRectMake(200-50, 250, 100.0, 40.0);///buton
            smallButton.frame   =CGRectMake(275, 200, 38, 38);//button
            pickerView.frame    =CGRectMake(0, 250+85, 320, 247);
        }
    }
    else
    {
        
        if(isLandScape==TRUE)
        {
            Title.center        =CGPointMake(250, 30+40);///center
            titleSearch.center  =CGPointMake(110, 80);/// left          
            inputDomain.frame   =CGRectMake(11, 100, 460, 24);//center
            titleTag.center     =CGPointMake(110, 150);/// left
            ChoiceTag.frame     =CGRectMake(11, 170, 460-40, 24);//center
            Search.frame        =CGRectMake(50+10, 205, 100, 40);//button
            Saving.frame        =CGRectMake(340-70, 205, 100, 40);//button
            smallButton.frame   =CGRectMake(435, 160, 38, 38);//button            
            pickerView.frame    =CGRectMake(0, 150, 480, 247);
        }
        else
        {
            Title.center        =CGPointMake(160, 30+50);/// center
            titleSearch.center  =CGPointMake(110, 100+20);/// left
            inputDomain.frame   =CGRectMake(11, 130+20, 299, 24);//center
            titleTag.center     =CGPointMake(110, 180+20);/// left
            ChoiceTag.frame     =CGRectMake(11, 210, 299-40, 24);//center
            Search.frame        =CGRectMake(30-10, 250, 100, 40.0);//button
            Saving.frame        =CGRectMake(200-50, 250, 100.0, 40.0);///buton
            smallButton.frame   =CGRectMake(275, 200, 38, 38);//button           
            pickerView.frame    =CGRectMake(0, 250, 320, 247);
        }
    }
    
}
#pragma mark - Reposition TabBar
- (void)repositionTabBar:(UIInterfaceOrientation)o {
	
	if (UIInterfaceOrientationIsLandscape(o)) {
		if (IS_IPHONE5) {
            ipTabBar.frame = CGRectMake(0, 250, 568, TABBAR_HEIGHT);
        }else
        {
             ipTabBar.frame = CGRectMake(0, 250, 480, TABBAR_HEIGHT);
            
        }
		
	} else {
		if (IS_IPHONE5) {
             ipTabBar.frame = CGRectMake(0,500 , 320, TABBAR_HEIGHT);
        }else
        {
            ipTabBar.frame = CGRectMake(0,410 , 320, TABBAR_HEIGHT);
           
        }
		
	}
	
}
#pragma mark - INIT DATA
-(void)initData
{
    arrayTag = [[NSMutableArray alloc] init];
    [arrayTag addObject:@".com"];
    [arrayTag addObject:@".com.vn"];
    [arrayTag addObject:@".biz.net"];
    [arrayTag addObject:@".edu.vn"];
    [arrayTag addObject:@".gov.vn"];
    [arrayTag addObject:@".net.vn"];
    [arrayTag addObject:@".org.vn"];
    [arrayTag addObject:@".int.vn"];
    [arrayTag addObject:@".ac.vn"];
    [arrayTag addObject:@".pro.vn"];
    [arrayTag addObject:@".info.vn"];
    [arrayTag addObject:@".health.vn"];
    [arrayTag addObject:@".name.vn"];
    [arrayTag addObject:@".angiang.vn"];
    [arrayTag addObject:@".bacgiang.vn"];
    [arrayTag addObject:@".backan.vn"];
    [arrayTag addObject:@".baclieu.vn"];
    [arrayTag addObject:@".bacninh.vn"];
    [arrayTag addObject:@".baria-vungtau.vn"];
    [arrayTag addObject:@".bentre.vn"];
    [arrayTag addObject:@".binhdinh.vn"];
    [arrayTag addObject:@".binhduong.vn"];
    [arrayTag addObject:@".binhphuoc.vn"];
    [arrayTag addObject:@".binhthuan.vn"];
    [arrayTag addObject:@".camau.vn"];
    [arrayTag addObject:@".cantho.vn"];
    [arrayTag addObject:@".caobang.vn"];
    [arrayTag addObject:@".daklak.vn"];
    
    [arrayTag addObject:@".daknong.vn"];
    [arrayTag addObject:@".danang.vn"];
    [arrayTag addObject:@".dienbien.vn"];
    [arrayTag addObject:@".dongnai.vn"];
    [arrayTag addObject:@".dongthap.vn"];
    [arrayTag addObject:@".gialai.vn"];
    [arrayTag addObject:@".hagiang.vn"];
    [arrayTag addObject:@".haiduong.vn"];
    [arrayTag addObject:@".haiphong.vn"];
    [arrayTag addObject:@".hanam.vn"];
    [arrayTag addObject:@".hanoi.vn"];
    [arrayTag addObject:@".hatay.vn"];
    [arrayTag addObject:@".hatinh.vn"];
    [arrayTag addObject:@".haugiang.vn"];
    [arrayTag addObject:@".hoabinh.vn"];
    
    [arrayTag addObject:@".hungyen.vn"];
    [arrayTag addObject:@".khanhhoa.vn"];
    [arrayTag addObject:@".kiengiang.vn"];
    [arrayTag addObject:@".komtum.vn"];
    
    [arrayTag addObject:@".laichau.vn"];
    [arrayTag addObject:@".lamdong.vn"];
    [arrayTag addObject:@".langson.vn"];
    [arrayTag addObject:@".laocai.vn"];
    [arrayTag addObject:@".longan.vn"];
    [arrayTag addObject:@".namdinh.vn"];
    [arrayTag addObject:@".nghean.vn"];
    [arrayTag addObject:@".ninhbinh.vn"];
    [arrayTag addObject:@".ninhthuan.vn"];
    [arrayTag addObject:@".phutho.vn"];
    [arrayTag addObject:@".phuyen.vn"];
    [arrayTag addObject:@".quangbinh.vn"];
    [arrayTag addObject:@".quangnam.vn"];
    [arrayTag addObject:@".quangngai.vn"];
    [arrayTag addObject:@".quangninh.vn"];
    [arrayTag addObject:@".quangtri.vn"];
    [arrayTag addObject:@".soctrang.vn"];
    [arrayTag addObject:@".sonla.vn"];
    [arrayTag addObject:@".tayninh.vn"];
    [arrayTag addObject:@".thaibinh.vn"];
    [arrayTag addObject:@".thainguyen.vn"];
    [arrayTag addObject:@".thanhhoa.vn"];
    [arrayTag addObject:@".thanhphohochiminh.vn"];
    [arrayTag addObject:@".thuathienhue.vn"];
    [arrayTag addObject:@".tiengiang.vn"];
    [arrayTag addObject:@".travinh.vn"];
    [arrayTag addObject:@".tuyenquang.vn"];
    [arrayTag addObject:@".vinhlong.vn"];
    [arrayTag addObject:@".vinhphuc.vn"];
    [arrayTag addObject:@".yenbai.vn"];
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
#pragma mark GADBannerViewDelegate impl
- (GADRequest *)createRequest
{
    GADRequest *request = [GADRequest request];
    request.testDevices =[NSArray arrayWithObjects:nil];
    return request;
}
// We've received an ad successfully.
- (void)adViewDidReceiveAd:(GADBannerView *)adView {
    NSLog(@"Received ad successfully");
}

- (void)adView:(GADBannerView *)view
didFailToReceiveAdWithError:(GADRequestError *)error {
    NSLog(@"Failed to receive ad with error: %@", [error localizedFailureReason]);
}
@end
